import React, { useState, useEffect } from 'react';
import {
  Box,
  Button,
  Card,
  CardBody,
  Flex,
  Heading,
  Radio,
  RadioGroup,
  Stack,
  Text,
  Textarea,
  useColorModeValue,
} from '@chakra-ui/react';
import Timer from '../components/practice/timer';
import Feedback from '../components/practice/feedback';
import questionsData from '../data/questions.json';
import { Question, PracticeAnswer } from '../types';

const Practice: React.FC = () => {
  const [questions, setQuestions] = useState<Question[]>([]);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [selectedAnswer, setSelectedAnswer] = useState('');
  const [answers, setAnswers] = useState<PracticeAnswer>({});
  const [showFeedback, setShowFeedback] = useState(false);
  const [timeLeft, setTimeLeft] = useState(300); // 5 minutes
  const [isTimerActive, setIsTimerActive] = useState(true);
  const cardBg = useColorModeValue('white', 'gray.700');
  const borderColor = useColorModeValue('gray.200', 'gray.600');

  useEffect(() => {
    setQuestions(questionsData as Question[]);
  }, []);

  useEffect(() => {
    let interval: NodeJS.Timeout | null = null;
    if (isTimerActive && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(time => time - 1);
      }, 1000);
    } else if (timeLeft === 0) {
      setIsTimerActive(false);
    }
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [isTimerActive, timeLeft]);

  const handleAnswerSelect = (value: string) => {
    setSelectedAnswer(value);
  };

  const handleSubmit = () => {
    if (!selectedAnswer) return;

    const newAnswers = {
      ...answers,
      [currentQuestionIndex]: selectedAnswer,
    };
    setAnswers(newAnswers);
    setShowFeedback(true);
  };

  const handleNext = () => {
    if (currentQuestionIndex < questions.length - 1) {
      setCurrentQuestionIndex(currentQuestionIndex + 1);
      setSelectedAnswer('');
      setShowFeedback(false);
    }
  };

  const handlePrev = () => {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex(currentQuestionIndex - 1);
      setSelectedAnswer(answers[currentQuestionIndex - 1] || '');
      setShowFeedback(false);
    }
  };

  const handleFinish = () => {
    // In a real app, this would save results and show summary
    alert('Practice session completed!');
  };

  if (questions.length === 0) {
    return (
      <Box textAlign="center" py={10}>
        <Text>Loading questions...</Text>
      </Box>
    );
  }

  const currentQuestion = questions[currentQuestionIndex];
  const isAnswered = Object.prototype.hasOwnProperty.call(answers, currentQuestionIndex);
  const isCorrect = isAnswered && answers[currentQuestionIndex] === currentQuestion.correctAnswer;

  return (
    <Box maxW="container.md" mx="auto">
      <Flex justifyContent="space-between" alignItems="center" mb={6}>
        <Heading as="h2" size="lg">
          Practice
        </Heading>
        <Timer timeLeft={timeLeft} />
      </Flex>

      <Card bg={cardBg} border="1px" borderColor={borderColor} mb={6}>
        <CardBody>
          <Flex justifyContent="space-between" alignItems="center" mb={4}>
            <Text fontWeight="bold">
              Question {currentQuestionIndex + 1} of {questions.length}
            </Text>
            <Text fontSize="sm" color="gray.500">
              {currentQuestion.type}
            </Text>
          </Flex>

          <Heading as="h3" size="md" mb={4}>
            {currentQuestion.question}
          </Heading>

          {currentQuestion.type === 'multiple-choice' && (
            <RadioGroup
              onChange={handleAnswerSelect}
              value={selectedAnswer}
              isDisabled={showFeedback}
            >
              <Stack direction="column" spacing={3}>
                {currentQuestion.options?.map((option, index) => (
                  <Radio key={index} value={option} colorScheme="brand">
                    {option}
                  </Radio>
                ))}
              </Stack>
            </RadioGroup>
          )}

          {currentQuestion.type === 'fill-in-blank' && (
            <Textarea
              value={selectedAnswer}
              onChange={e => handleAnswerSelect(e.target.value)}
              placeholder="Type your answer here..."
              isDisabled={showFeedback}
              rows={3}
            />
          )}

          {showFeedback && (
            <Feedback
              isCorrect={isCorrect}
              correctAnswer={currentQuestion.correctAnswer}
              explanation={currentQuestion.explanation}
            />
          )}

          <Flex justifyContent="space-between" mt={6}>
            <Button
              onClick={handlePrev}
              isDisabled={currentQuestionIndex === 0}
              colorScheme="brand"
              variant="outline"
            >
              Previous
            </Button>

            {!showFeedback ? (
              <Button onClick={handleSubmit} isDisabled={!selectedAnswer} colorScheme="brand">
                Submit
              </Button>
            ) : currentQuestionIndex < questions.length - 1 ? (
              <Button onClick={handleNext} colorScheme="brand">
                Next
              </Button>
            ) : (
              <Button onClick={handleFinish} colorScheme="green">
                Finish
              </Button>
            )}

            <Button
              onClick={handleNext}
              isDisabled={currentQuestionIndex === questions.length - 1}
              colorScheme="brand"
              variant="outline"
            >
              Next
            </Button>
          </Flex>
        </CardBody>
      </Card>
    </Box>
  );
};

export default Practice;
